package cm309.BookingSystem.tm.web.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cm309.BookingSystem.common.Common;
import cm309.BookingSystem.common.MyConnection;
import cm309.BookingSystem.tm.model.Trainer;
import cm309.BookingSystem.web.Action;


public class CreateTMAction implements Action {

	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		MyConnection con=new MyConnection();

		
		try {
			//get the least trainerID number
			Long oldtrainerIDnum;
			String trainerConnt=con.getOneField(
					"Select Count(TrainerID) from BK_TM_TRAINER");
			
			if (Long.parseLong(trainerConnt)>0) {
				oldtrainerIDnum=Long.parseLong(con.getOneField(
						"Select TrainerID from BK_TM_TRAINER order by TrainerID DESC"));
			} else {
				oldtrainerIDnum=(long)1;
			}
			//update
			PreparedStatement ps=con.getPS(
					"INSERT INTO BK_TM_TRAINER ( TRAINERNAME, TRAINERGENDER" +
					",TRAINERAGE,CLASSIFICATION ,TRAINERID) VALUES (?,?,?,?,?)");
			
			//set the Trainer
			Trainer t=new Trainer();
			String formatStr="%08d";
			
			t.setTrainerID(String.format(formatStr, oldtrainerIDnum+1));		
			t.setTrainerName(request.getParameter("trainerName"));
			t.setTrainerGender(request.getParameter("trainerGender").charAt(0));
			t.setTrainerAge(Integer.parseInt(request.getParameter("trainerAge")));
			t.setClassification(request.getParameter("classification"));
			

			ps.setString(1, t.getTrainerName());
		    ps.setString(2,Character.toString(t.getTrainerGender()));
			ps.setInt(3,t.getTrainerAge());
			ps.setString(4,t.getClassification());
			ps.setString(5,t.getTrainerID());
			int count=ps.executeUpdate();
			if (count!=1) {
				throw new RuntimeException("Insert Trainer Error");
			}
			
			con.commit();
	
			 //redirect to the show product!
			PrintWriter w = response.getWriter();
		
			w.println(Common.beanToJson(t));
			  			
		} catch (SQLException e) {

			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally {
			
			con.close();
		}

	}

}
